package online.lona.mc.mod.ymer;


import io.netty.buffer.ByteBuf;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.*;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.FMLEventChannel;
import net.minecraftforge.fml.common.network.FMLNetworkEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import online.lona.mc.LibraryUtil;
import online.lona.mc.NativeInterface;

import java.lang.reflect.Field;

@Mod(modid = Ymer.MODID, version = NativeInterface.VERSION, acceptedMinecraftVersions = "[1.8,1.12.2]")
public class Ymer {
    public static final String MODID = "ymer";
    public static FMLEventChannel channel = null;
    private ServerMessageQueue messageQueue = new ServerMessageQueue();

    @Mod.EventHandler
    public void modMain(FMLInitializationEvent event) {
        final String libraryPath = System.getProperty("user.dir") + "/mods";
        LibraryUtil.releaseLibrary(libraryPath);
        try {
            LibraryUtil.addLibraryDir(libraryPath);
        } catch (Exception e) {
            System.out.println("无法设置库路径");
            return;
        }
        MinecraftForge.EVENT_BUS.register(this);
        FMLCommonHandler.instance().bus().register(this);
        (channel = NetworkRegistry.INSTANCE.newEventDrivenChannel(NativeInterface.CHANNEL_NAME)).register(this);
        if (event.getSide() == Side.CLIENT)
            new Thread(() -> NativeInterface.clientInit(new StandardYmerServer())).start();
    }

    @SubscribeEvent(priority = EventPriority.LOWEST)
    @SideOnly(Side.CLIENT)
    public void onServerCustomPacket(FMLNetworkEvent.ClientCustomPacketEvent event) {
        try {
            final Field packetFleid = event.getClass().getSuperclass().getDeclaredField("packet");
            final FMLNetworkEvent.CustomPacketEvent customPacketEvent = event;
            packetFleid.setAccessible(true);
            final FMLProxyPacket packet = (FMLProxyPacket) packetFleid.get(customPacketEvent);
            if (packet.channel().equals(NativeInterface.CHANNEL_NAME)) {
                ByteBuf buffer = packet.payload();
                byte[] data = new byte[buffer.readableBytes()];
                buffer.readBytes(data);
                messageQueue.newMessageIncoming(data);
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }


}
